/**
 * 导航栏
 * @author zido
 * @since 2017/6/2 0002
 */
import React from 'react'
import {Menu, Icon} from 'antd'
import {Link} from 'react-router'
import Util from '../../Util'
import PropTypes from 'prop-types'
import './Nav.less'
const SubMenu = Menu.SubMenu

export default class Nav extends React.Component {
  handleData(data,depth = 0) {
    return data.map((value, index) => (
      (value.children instanceof Array) ?
        <SubMenu key={'sub'+index+'and'+depth} title={<span>{typeof(value.icon) === 'string' ?
          <Icon type={value.icon}/> : value.icon}<span className="nav-text">{value.text}</span></span>}>
          {this.handleData(value.children,depth++)}
        </SubMenu> :
        <Menu.Item key={'nav' + index+'and'+depth}>
          <Link to={value.link}>
            {typeof(value.icon) === 'string' ? <Icon type={value.icon}/> : value.icon}
            <span className="nav-text">{value.text}</span>
          </Link>
        </Menu.Item>
    ))
  }

  handleSelect(routes,data,depth = 0){
    let select = []
    if (routes.length > 1) {
      data.map((data, index) => {
        if(Util.isEmpty(data.link)){
          select.push(...(this.handleSelect(routes,data.children,depth+1)))
          return true
        }
        if (data.link === routes[1].path) {
          select.push('nav' + index + 'and' + depth)
        }
      })
    }
    if(select.length === 0)
      select.push('nav0and0')
    return {
      select:select
    }
  }

  render() {
    const {routes, data} = this.props
    let {select,open} = this.handleSelect(routes,data)
    return (
      <div>
        <div className="main-logo"/>
        <Menu className="nav-info" theme="dark" mode="inline" defaultSelectedKeys={select} defaultOpenKeys={open}>
          {this.handleData(data)}
        </Menu>
      </div>
    )
  }
}

Nav.propTypes = {
  routes: PropTypes.array,
  data: PropTypes.array.isRequired
}